package com.example.Controller;

import com.example.Result.AllResult;
import com.example.Service.TableService;;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;


@RestController
public class TableController {
    @Autowired
    private TableService tableService;
    @GetMapping("/gettable")
    public AllResult getUser(){
        return AllResult.allResult(1,"message",tableService.getUser());
    }
    @DeleteMapping("/delete/{id}")
    public AllResult deleteUser(@PathVariable int id){

        return AllResult.allResult(tableService.deleteUser(id),"message",null);
    }
    @PostMapping("/upload")
    protected AllResult doPost(@RequestParam("file") MultipartFile file) {
        String uploadPath = "D:\\21319\\Pictures\\Saved Pictures";  // 设置文件保存路径
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        try {
            String fileName = file.getOriginalFilename();  // 获取上传文件的文件名
//            String fileExtension = getFileExtension(fileName); // 获取文件后缀名
//            使用 id_type + 原始后缀名 组成新的文件名
//            String newFileName = id + "_" + type + fileExtension;
            String filePath = uploadPath + File.separator + fileName;
            File existingFile = new File(filePath);
            if (existingFile.exists()) {
//                existingFile.delete(); // 删除已存在的文件
                return AllResult.allResult(0, "重复上传,请更改文件名或选择其他文件", null);
            }
            // 将文件保存到指定路径下
            file.transferTo(new File(filePath));
            return AllResult.allResult(1, "文件上传成功,文件名：" + fileName, null);
        } catch (Exception e) {
            return AllResult.allResult(0, "文件上传失败:" + e.getMessage(), null);
        }
    }

    // 辅助方法：获取文件的后缀名
//    private String getFileExtension(String fileName) {
//        int dotIndex = fileName.lastIndexOf(".");
//        if (dotIndex > -1 && dotIndex < fileName.length() - 1) {
//            return fileName.substring(dotIndex);
//        }
//        return "";
//    }
}
